<?php
// +----------------------------------------------------------------------
// | 随访系统
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2050 http://www.hedesoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +---------------------------------------------------------------------
// | Author: 小李子 < 490959289@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;
use app\admin\controller\Base;
use think\Validate;
use org\Upload;
class Article extends Base
{
    public function index()
    {
    	$where = array();
    	$where['is_del'] = 0;
    	$key = $this->request->param('key');
    	if ($key){
    		 $where['post_title'] = array('LIKE', '%'.$key.'%');
    	}
    	$list=model('Article')->where($where)->order('ctime desc')->paginate(15);
    	foreach ($list as $key => $value) {
    		// $data=model('Article')->where('diseases_id='.$value['w_diseases_id'])->field('diseases_name')->find();
    		// $list[$key]['Article'] = $data['diseases_name'];
            $list[$key]['dt'] = date("Y-m-d H:i:s",$value['ctime']);
            $list[$key]['uptime'] = $value['update_time'];
        }
    	$this->assign('list', $list);
    	// $this->assign('data', $data);
    	return $this->fetch();
    }
    public function add()
    {
       	$list  = model('ArticleCategory')->where(['parent_id'=>0,'is_del'=>0])->order('ctime',' asc')->select();
        if ($list){
            foreach ($list as $key => $val) {
                $list[$key]['next'] = model('ArticleCategory')->where(['parent_id'=>$val['category_id'],'is_del'=>0])->order('ctime',' asc')->select();
            }
        }
       	$this->assign('list', $list);
        $attr = model('Attribute')->getAttrData(['yes_no']);
        $this->assign('attr', $attr);
    	return $this->fetch();
    }
    //分类弹窗
    public function category_form(){
        $check_id = $this->request->param('check_id');
        $checkId = explode(',',$check_id);
        $list  = model('ArticleCategory')->where(['parent_id'=>0,'is_del'=>0])->order('ctime',' asc')->select();
        if ($list){
            foreach ($list as $key => $val) {
                $list[$key]['next'] = model('ArticleCategory')->where(['parent_id'=>$val['category_id'],'is_del'=>0])->order('ctime',' asc')->select();
            }
        }
        $this->assign('checkId', $checkId);
        $this->assign('list', $list);
        return $this->fetch();
    }
    public function mergeParam()
    {
        $data = array();
        $w_category_id = $_POST['w_category_id'];
        foreach ($w_category_id as $key => $name) {
            $data_id[] = $key;
            $data[] = array(
                'data_id'=>$key,
                'data_name'=>$name,
            );
        }
        echo json_encode(array('data_id'=>implode(',', $data_id),'data'=>$data));
    }
    //编辑功能
    public function edit()
    {
    	$article_id = $this->request->param('article_id');
        $power=model('Article')->get($article_id);
        $imgJson = json_decode($power['post_ext']);
        if ($imgJson) {
           $img = implode(',',$imgJson);
        }else{
          $img ='';  
        }
        // print_r($img);die;
        //分类管理
        $check_power=[];
        if(!empty($power)){
            $check_powers=$power->question;
            foreach($check_powers as $g){
                // 获取中间表数据
                $check_power=$g->pivot->where('w_article_id',$article_id)->column('w_category_id');
            }
        }
        $category_name=array();
        foreach ($check_power as $key => $value) {
            $category = model('ArticleCategory')->where('category_id',$value)->column('category_name');
            array_push($category_name,$category[0]);
        }
        $this->assign('category_name', $category_name);
        $list  = model('ArticleCategory')->where(['parent_id'=>0,'is_del'=>0])->order('ctime',' asc')->select();
        if ($list){
            foreach ($list as $key => $val) {
                $list[$key]['next'] = model('ArticleCategory')->where(['parent_id'=>$val['category_id'],'is_del'=>0])->order('ctime',' asc')->select();
            }
        }
        $attr = model('Attribute')->getAttrData(['yes_no']);
        $this->assign('attr', $attr);
       	$this->assign('check_id', implode(',',$check_power));
        $this->assign('list', $list);
       	$this->assign('data', $power);
        $this->assign('img', $img);
    	return $this->fetch();
    }

    //添加模板数据
    public function add_data()
    {
    	$model = model('Article');
		$model->startTrans();//开启事务
		try{
			$rule = [
	            'post_title'  => 'require',
	            'post_content'  => 'require',
	        ];

	        $msg = [
	            'post_title.require' => '文章标题不能为空',
	            'post_content' => '文章内容不能为空',
	        ];
	        $data['post_title'] = $this->request->param('post_title');
		    $data['post_content'] = $this->request->param('post_content');
            $data['post_source'] = $this->request->param('post_source');
            $data['seo_description'] = $this->request->param('seo_description');
            $data['seo_keywords'] = $this->request->param('seo_keywords');
            $data['post_ext'] = $this->request->param('post_ext');
            $data['status'] = $this->request->param('status');
	        $validate = new Validate($rule, $msg);
	        if (!$validate->check($data)){
	            echo json_encode(['status'=>0,'msg'=>$validate->getError()]);exit();
	        }
	        $article_id = $this->request->param('article_id');
	        if ($article_id) {
	        	$add_id = $article_id;
                $data['update_time'] = time();
	        	$edit_id = $model->where('article_id',$article_id)->update($data);//录入数据库
	        }else{
	        	$data['is_del'] = 0;
		        $data['ctime'] = time();
                $data['update_time'] = time();
		        $add_id = $model->insertGetId($data);//录入数据库
		        
		    }
            $w_category_id = $this->request->param('w_category_id');
            $cat_type = explode(',',$w_category_id);
            $where['w_article_id'] = $article_id;
	        $del_num = model('ArticleCategoryLink')->where($where)->delete();
	        $dataArr = array();
	        for ($i=0; $i < count($cat_type); $i++) {
	        	if ($cat_type[$i]) {
	        	 	$dataArr[] = [
		                'w_category_id'=>$cat_type[$i],
		                'w_article_id'=>$add_id,
	                ];
	        	 }      
	        }
		    model('ArticleCategoryLink')->saveAll($dataArr);//录入问题答案
	        // 提交事务
	        $model->commit();
       	} catch (\Exception $e) {
            // 回滚事务
            $model->rollback();
            echo json_encode(array('status'=>0,'msg'=>$e->getMessage()));exit();
        }
    	echo json_encode(array('status'=>1,'msg'=>'保存成功'));
    }

    //删除模板数据
    public function delTemp(){
    	$model = model('Article');
    	$data['article_id'] = $this->request->param('article_id');
    	$data['is_del'] = 1;
    	$save['is_del'] = 1;
    	// $where['w_template_id'] = $this->request->param('article_id');
    	$attr_status = $model->update($data);
    	// $attr_status = model('PhoneQuestion')->where($where)->update($save);
    	if ($attr_status){
    		$this->create_adminlog('删除模板ID：'.$data['article_id'].'');
    		echo json_encode(['status'=>1,'msg'=>'删除成功']);exit();
    	}else{
    		echo json_encode(['status'=>0,'msg'=>'删除失败']);exit();
    	}
    }
    //文件上传
    function upload(){
        $file = $this->request->file('file');//file是传文件的名称，这是webloader插件固定写入的。因为webloader插件会写入一个隐藏input，不信你们可以通过浏览器检查页面
        $file->rule('time');
        $dirname = date('Ymd',time());
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . $dirname);
        $path = 'uploads/'.$dirname.'/'.$info->getFilename();
        if ($path) {
            echo json_encode(['status' => 200, 'msg' => '上传成功！', 'data' => $path]);
        } else {
            //是专门来获取上传的错误信息的
            //$this->error($upload->getErrorMsg());
            //echo $upload->getErrorMsg();
            echo json_encode(['status' => 200, 'msg' => '上传成功！', 'data' =>123]);
        }
        
    }
    
    
}
